<script setup>
import List from '../components/List.vue'
import ClusterNamespaceSelector from "../components/ClusterNamespaceSelector.vue";
import {getPodListHandler as getListHandler,deletePodHandler as deleteHandler} from "../../api/pod.js";
import {reactive, computed, ref, toRefs} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import CodeMirror from "../components/CodeMirror.vue";
import {obj2Yaml} from "../../utils/utils.js";

const search = ref('')
const  data = reactive({
  items: [],
  clusterId: "",
  namespace: "",
  yamlContent: "",
})
// 定义一个查询pod列表的函数
const getList=()=>{
  getListHandler(data.clusterId,data.namespace).then(
      (res)=>{
        data.items = res.data.data.items
        console.log("11res:",res)
        console.log("11items: ",data.items)
      }
  )
}
// 回调函数 让组件调用这个回调函数
const rollback = (clusterId,namespace)=>{
  data.namespace = namespace
  data.clusterId = clusterId
  getList()
}
// 搜索的逻辑
const filterTableData = computed(() =>
    data.items.filter(
        (item) =>
            !search.value ||
            item.metadata.name.toLowerCase().includes(search.value.toLowerCase())
    )
)
// 删除的方法
const  deleteItem=(row,force)=>{
  console.log("删除：",row)
  ElMessageBox.confirm(
      `你确定要删除命名空间： ${data.namespace} Pod: ${row.metadata.name} 吗？`,
      {
        confirmButtonText: "确认",
        cancelButtonClass: "取消",
        type: "warning",
      }
  ).then(()=>{
    deleteHandler(data.clusterId,data.namespace,row.metadata.name,force).then((response)=>{
      ElMessage({
        message: response.data.message,
        type: 'warning',
      })
      getList()
    })
  }).catch((err)=>{
    return err
  })
}
// 判断pod的重启次数和容器状态  使用计算属性
const getPodRestartCount = computed(()=>(row)=>{
  console.log("row:",row)
  let restartCount = 0
  let readyCount = 0
  row.status.containerStatuses.forEach(item => {
    restartCount += item.restartCount
    if (item.ready){
      // 当前容器已经重启完成
      readyCount += 1
    }
  })
  // 当前pod中的容器总数
  const containerTotal = row.status.containerStatuses.length
  const readyStatus = `${readyCount}/${containerTotal}`

  return [restartCount,readyStatus];
})
// 展示pod详情
const showDetail = ref(false)
const detail = (row)=>{
  // 在展示pod的yaml前对pod 做一次加工
  // 对数据做一个深度拷贝
  const item = JSON.parse(JSON.stringify(row));
  // 删除managedFields
  delete item.metadata.managedFields

  // 把apiVersion kind补上去
  const itemTemp = {
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": item.metadata,
    "spec": item.spec
  }


  showDetail.value=true

  // 把当前数据转成yaml
  const yamlData = obj2Yaml(itemTemp)
  data.yamlContent = yamlData

}
const {yamlContent} = toRefs(data)
</script>




<template>
  <List title="Pod列表">
    <!-- #handler-options 选择list组件中 handler-options插槽的位置   -->
    <template #handler-options>
      <ClusterNamespaceSelector @namespaceChangedRollback="rollback"></ClusterNamespaceSelector>
      <el-input v-model="search" size="small" placeholder="搜索"  style="width:200px;height: 32px; margin-left: 20px"/>
    </template>
    <template #main>
      <!--  放真实数据的地方  -->
      <!--   默认排序的字段default-sort   -->
      <el-table
          border
          height="480"
          :data="filterTableData"
          style="width: 100%"
          :default-sort="{prop: 'metadata.creationTimestamp', order: 'descending'}"
      >

        <!--  align="center" 表格中居中  sortable 排序    -->
        <el-table-column fixed  prop="" align="center"  label="名称"  width="300">
          <!--   router-link 实现在点击集群id的时候路径跳转     -->
          <template #default="scope">
            <el-button link type="primary" size="small" @click="detail(scope.row)">{{ scope.row.metadata.name }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="metadata.creationTimestamp" align="center"  label="创建时间" sortable />
        <el-table-column prop="metadata.namespace" align="center"  label="命名空间" />
        <el-table-column prop="" align="center"  label="状态" >
          <template #default="scope">
            <el-icon v-if ="scope.row.status.phase === 'Running'" style="color: green">{{scope.row.status.phase}}</el-icon>
            <el-icon v-else style="color: red">{{scope.row.status.phase}}</el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="" align="center"  label="重启次数" >
          <template #default="scope">
              <span v-if="!scope.row.metadata.deletionTimestamp">{{ getPodRestartCount(scope.row)[0] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="" align="center" label="容器状态" >
          <template #default="scope">
            <span v-if="!scope.row.metadata.deletionTimestamp">{{ getPodRestartCount(scope.row)[1] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status.podIP" align="center"  label="Pod IP"  />
        <el-table-column prop="spec.nodeName" align="center"  label="宿主机主机名" sortable />
        <el-table-column prop="status.hostIP" align="center"  label="宿主机IP" sortable />
        <el-table-column fixed="right" align="center"  label="操作" width="240" >
          <!--  插槽的 scope 可以绑定行的数据  scope.row 获取一行的数据    -->
          <template #default="scope">
            <el-button v-if="!scope.row.metadata.deletionTimestamp" link type="warning" size="small" @click="deleteItem(scope.row,false)">删除</el-button>
            <el-button v-else link type="warning" size="small" @click="deleteItem(scope.row,true)">强制删除</el-button>
            <el-button v-if="!scope.row.metadata.deletionTimestamp" link type="primary" >执行命令</el-button>
            <el-button v-if="!scope.row.metadata.deletionTimestamp" link type="primary" >查看日志</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </List>
  <!--  pod的详情  -->
  <el-dialog
      destroy-on-close
      v-model="showDetail"
      width="70%">
        <template #header="{titleId, titleClass }">
          <div class="my-header">
            <div :id="titleId" :class="titleClass" style="margin: 5px auto 0 auto">
              <el-button type="primary"  title="资源所在的集群">
                  <i class="iconfont icon-kubernetes" style="font-size: 20px;" />
                  <span style="font-size: 20px; ">{{data.clusterId}}</span>
              </el-button>
              <el-button type="primary"  title="资源所在的命名空间">
                <i class="iconfont icon-kubernetes" style="font-size: 20px;" />
                <span style="font-size: 20px; ">{{data.namespace}}</span>
              </el-button>
            </div>
          </div>
        </template>
        <CodeMirror
            v-model="yamlContent"
        ></CodeMirror>
  </el-dialog>
</template>

<style scoped>
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
}
</style>